package org.lhh.server.config.web.exception;

import org.lhh.server.common.api.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.UnknownHostException;


@ControllerAdvice
public class ServerException {

    private static final Logger log = LoggerFactory.getLogger(ServerException.class);

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public JSONResult systemException(Exception ex) {
        log.error(ex.getMessage(),ex);
        if (ex instanceof UnAuthorizedException) {
            return JSONResult.errorTokenMsg(ex.getMessage());
        } else if (ex instanceof UnPermissionException) {
            return JSONResult.errorMsg(ex.getMessage());
        } else if (ex instanceof MethodArgumentNotValidException) {
            return JSONResult.errorMsg(parseBindingResult(((MethodArgumentNotValidException) ex).getBindingResult()));
        } else if (ex instanceof BindException) {
            return JSONResult.errorMsg(parseBindingResult(((BindException) ex).getBindingResult()));
        } else if (ex instanceof UnknownHostException) {
            return JSONResult.errorMsg("未知IP或者域名");
        } else if (ex instanceof BaseException) {
            return JSONResult.errorMsg(ex.getMessage());
        }else if (ex instanceof ErrorException) {
            return JSONResult.errorException(ex.getMessage());
        }else if (ex instanceof EtlException) {
            return JSONResult.errorEtlMsg(ex.getMessage());
        }else if (ex instanceof TestException) {
            return JSONResult.errorTestMsg(ex.getMessage());
        }
        return JSONResult.errorMsg("系统异常");
    }

    private String parseBindingResult(BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = (FieldError) result.getAllErrors().get(0);
            fieldError.getObjectName();
            fieldError.getField();
            return fieldError.getDefaultMessage();
        }
        return "系统异常";
    }
}
